package com.jy.api.service.impl;

import com.jy.api.domain.StoreOrder;
import com.jy.api.enums.PayTypeEnum;
import com.jy.api.pay.request.PayRequest;
import com.jy.api.pay.result.PayResult;
import com.jy.api.service.PayService;
import com.jy.api.util.ObjectToMap;
import com.jy.api.util.Payutils;
import com.jy.api.util.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * Created by lihu on 2017/10/7.
 */
@Slf4j
@Service
public class PayServiceImpl implements PayService {


    @Autowired
    Payutils payutils;


    @Autowired
    RestTemplate restTemplate;

    @Override
    public PayResult StoreQRCode(StoreOrder storeOrder) throws Exception {
        //初始化请求实体
        PayRequest payRequest = new PayRequest(PayTypeEnum.PAY_WX_NATIVE.getCode(), "399520227696",
                storeOrder.getId(), "店铺活动收费！",
                storeOrder.getAmount(), storeOrder.getIp(),
                payutils.getStoreNotifyUrl());
        payRequest.setService("unified.trade.native");
        payRequest.setAttach("STOREORDER");
        payRequest.setUpSign(ObjectToMap.objectToMap(payRequest), "8de420f99019656a1f6da0412b49f01b");
        log.info("QRCode PayRequest:{}", payRequest);
        String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, payRequest.toXML(), String.class).getBody();
        PayResult payResult = XmlUtils.fromXML(xml, PayResult.class);
        return payResult;
    }

    @Override
    public PayResult MyQRCode(String ip, String type,
                              String rechargeId, int amount) throws Exception {
        //初始化请求实体
        PayRequest payRequest = new PayRequest(type, rechargeId, ip, payutils.getStoreRecharge(), amount);
        payRequest.setUpSign(ObjectToMap.objectToMap(payRequest), "8de420f99019656a1f6da0412b49f01b");
        log.info("MyQRCode PayRequest:{}", payRequest);
        String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, payRequest.toXML(), String.class).getBody();
        PayResult payResult = XmlUtils.fromXML(xml, PayResult.class);
        return payResult;
    }


    @Override
    public PayResult webQuery(String id) throws Exception {

        //初始化请求实体
        PayRequest payRequest = new PayRequest(PayTypeEnum.UNIFIED_TRADE_QUERY.getCode(),
                "399520227696", id);
        payRequest.setUpSign(ObjectToMap.objectToMap(payRequest), "8de420f99019656a1f6da0412b49f01b");
        log.info("webQuery PayRequest:{}", payRequest);
        String xml = restTemplate.postForEntity(Payutils.ALI_QR_CODE, payRequest.toXML(), String.class).getBody();
        PayResult queryResult = XmlUtils.fromXML(xml, PayResult.class);
        return queryResult;
    }

}
